package com.ch4;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author woldier
 * @version 1.0
 * @description wait-notify 设计模式 保护性暂停
 * @date 2023/5/5 8:51
 **/
@Slf4j(topic = "c.Thread")
public class Demo06 {
    public static void main(String[] args) throws InterruptedException {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(()->{
            guardedObject.getResponse();

        },"消费者").start();
        TimeUnit.SECONDS.sleep(6);
        new Thread(()->{
            guardedObject.complete("hello");

        },"生产者").start();
    }


}
/**
 * 保护性对象
 */
@Slf4j(topic = "c.Thread")
class GuardedObject {
    private Object response;

    /**
     * description 同步性线程 消费者 加入超时时间
     *
     * @return java.lang.Object
     * @author: woldier
     * @date: 2023/5/5 8:55
     */
    public synchronized Object getResponse(long timeout) {
        while (response == null) {
            log.debug("消费者等待生产者");
            try {
                this.wait(timeout);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        log.debug("消费者消费成功");
        return response;
    }

    /**
    *
    * description 同步性线程 消费者 默认超时时间 6000 ms
    *
    *
    * @return java.lang.Object
    * @author: woldier
    * @date: 2023/5/5 13:11
    */
    public synchronized Object getResponse() {
       return getResponse(6000);
    }


    /**
     * description 同步线程 生产者
     *
     * @param o 生产者产生的结果
     * @return void
     * @author: woldier
     * @date: 2023/5/5 8:56
     */
    public synchronized void complete(Object o) {
        response = o;
        this.notifyAll();
        log.debug("生产者");
    }
}



